<template>
  <div class="menu">
    <div class="menu-title">
      系统选择：
      <Select v-model="selectSysCode" @on-select="handleOnSelect" style="width:180px">
        <Option v-for="item in menuServices" :value="item" :key="item">{{ item }}</Option>
      </Select>
      <Button style="margin-left: 10px;" @click="handelRefresh" size="small" type="primary" shape="circle" icon="ios-refresh">刷新</Button>
    </div>
    <Row :gutter="16">
      <Col :xs="24" :sm="24" :md="10" :lg="10" class="menu-col">
        <Card dis-hover>
          <p slot="title"><Icon type="md-list" /> 菜单树</p>
          <div slot="extra">
            <Dropdown style="margin-left: 20px; margin-right: 15px;" @on-click="handleDropClick">
              <a href="javascript:void(0)">
                添加菜单
                <Icon type="ios-arrow-down"></Icon>
              </a>
              <DropdownMenu slot="list">
                <DropdownItem name="parentMenu">添加顶栏菜单</DropdownItem>
                <DropdownItem name="childMenu" :disabled="disabled">添加子菜单</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            <Tag color="error" style="cursor: pointer;" @click.native="handleTagClick">删除</Tag>
            <Tag color="primary" style="cursor: pointer;" @click.native="handleRefresh">刷新</Tag>
          </div>
          <div class="menu-box">
            <Tree
              ref="tree"
              :data="menuData"
              show-checkbox
              select-node
              :check-strictly="true"
              @on-select-change="onSelectChange"
            >
            </Tree>
          </div>
        </Card>
      </Col>
      <Col :xs="24" :sm="24" :md="12" :lg="12" class="menu-col">
        <Card dis-hover>
          <p slot="title"><Icon type="md-list" /> 编辑菜单：{{currentMenu == '' ? '':currentMenu.title}}</p>
          <Alert v-show="selectNodes.length == 0">从菜单列表选择一项后，进行编辑</Alert>
          <Form :model="formItem" ref="formInline" :rules="ruleInline" label-colon :label-width="80" v-show="selectNodes.length > 0">
            <FormItem label="类型">
              <p>侧边栏菜单</p>
            </FormItem>
            <FormItem label="标题" prop="title">
              <Input v-model="formItem.title" placeholder="请输入菜单标题"/>
            </FormItem>
            <FormItem label="路由" prop="name">
              <Input v-model="formItem.name" placeholder="请输入路由名称"/>
            </FormItem>
            <FormItem label="系统码" prop="sysCode">
              <Input v-model="formItem.sysCode" placeholder="请输入系统码"/>
            </FormItem>
            <FormItem label="图标">
              <Input v-model="formItem.icon" placeholder="请输入图标代码"/>
            </FormItem>
            <FormItem label="使用外链">
              <i-switch v-model="outPathSwitch" size="large" @on-change="switchChange">
                <span slot="open">开</span>
                <span slot="close">关</span>
              </i-switch>
            </FormItem>
            <FormItem label="地址" v-show="outPathSwitch">
              <Input v-model="outPath" placeholder="请输入外链地址"/>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleUpdateMenu">
                <span v-if="!loading">保存修改</span>
                <span v-else>正在保存</span>
              </Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>

    <!-- 添加菜单 -->
    <div class="add-menu">
      <Modal
        v-model="addMenuModel"
        title="添加菜单"
        @on-ok="handelAddMenu"
        @on-cancel="cancelAdd"
      >
        <Form ref="formInlineMenu" label-colon :label-width="80" :model="formDataMenu" :rules="ruleInlineMenu">
          <FormItem label="父级菜单" v-show="selectNodes.length > 0">
            <p>{{currentMenu == '' ? '':currentMenu.title}}</p>
          </FormItem>
          <FormItem label="标题" prop="title">
            <Input v-model="formDataMenu.title" placeholder="请输入菜单标题"/>
          </FormItem>
          <FormItem label="路由" prop="name">
            <Input v-model="formDataMenu.name" placeholder="请输入路由名称"/>
          </FormItem>
          <FormItem label="系统码" prop="sysCode">
            <Input v-model="formDataMenu.sysCode" placeholder="请输入系统码"/>
          </FormItem>
          <FormItem label="图标">
            <Input v-model="formDataMenu.icon" placeholder="请输入图标代码"/>
          </FormItem>
          <FormItem label="外链地址">
            <Input v-model="formDataMenu.outPath" placeholder="请输入外链地址"/>
          </FormItem>
        </Form>
      </Modal>
    </div>

    <!-- 加载等待 -->
    <Spin fix v-show="show">
      <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
      <div>加载中...</div>
    </Spin>
  </div>
</template>

<script>
import {getAllMenuData,checkTitle,checkName,updateMenu,addMenu,deleteMenu,menuServices} from '@/api/menu'
import {getPath} from '@/api/outPath'

export default {
  name: 'Menu',
  data(){
    /**
     * 校验菜单标题是否已存在
     */
    const validateTitle = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkTitle(this.formItem.id,value).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }

    /**
     * 校验菜单路由是否已存在
     */
    const validateName = (rule, value, callback) => {
      if(value && value.trim() != ''){
        checkName(this.formItem.id, value).then(res => {
          if(res.data.status){
            callback()
          }else{
            callback(new Error(res.data.msg))
          }
        })
      }else{
        callback()
      }
    }

    return {
      menuData:[],
      disabled: true,
      currentMenu: '',
      selectNodes: [],
      formItem: {
        title: '',
        name: '',
        icon: '',
        sysCode: ''
      },
      outPathSwitch: false,
      outPath: '',
      ruleInline: {
        title: [
          { required: true, message: '标题不能为空'},
          { validator: validateTitle, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '路由不能为空'},
          { validator: validateName, trigger: 'blur' }
        ],
        sysCode: [
          { required: true, message: '系统码不能为空'}
        ]
      },
      loading: false,
      addMenuModel: false,
      formDataMenu: {
        title: '',
        name: '',
        icon: '',
        sysCode: '',
        outPath: ''
      },
      ruleInlineMenu: {
        title: [
          { required: true, message: '标题不能为空'}
        ],
        name: [
          { required: true, message: '路由不能为空'}
        ],
        sysCode: [
          { required: true, message: '系统码不能为空'}
        ]
      },
      selectSysCode: '',
      menuServices: [],
      show: true
    }
  },
  methods:{
    /**
     * 查询菜单数据
     */
    queryMenuData(sysCode){
      this.show = true
      getAllMenuData(sysCode).then(res => {
        this.show = false
        if(res.data.status){
          this.menuData = res.data.data
        }
      }).catch(()=>{
        this.show = false
      })
    },
    /**
     * 菜单节点选中触发
     */
    onSelectChange(arr,item){
      this.selectNodes = this.$refs.tree.getSelectedNodes()
      if(this.selectNodes.length == 0){
        this.disabled = true
        this.currentMenu = ''
      }else{
        this.outPathSwitch = false
        this.disabled = false
        this.currentMenu = item
        this.formItem = {...item}
      }
    },
    /**
     * 使用外链开关
     */
    switchChange(state){
      if(state){
        getPath(this.formItem.name).then(res =>{
          if(res.data.status && res.data.data){
            this.outPath = res.data.data.path
          }
        })
      }
    },
    /**
     * 保存修改的菜单数据
     */
    handleUpdateMenu(){
      this.$refs['formInline'].validate((valid) => {
        if(valid){
          this.loading = true
          let data = {
            id: this.formItem.id,
            title: this.formItem.title,
            name: this.formItem.name,
            icon: this.formItem.icon,
            sysCode: this.formItem.sysCode
          }
          if(this.outPath && this.outPath.trim() != ''){
            data.outPath = this.outPath
          }
          updateMenu(data).then(res => {
            this.loading = false
            if(res.data.status){
              this.$Message.success('修改成功')
              this.getMenuService(this.formItem.sysCode)
              this.formItem = {title: '',name: '',icon: '',sysCode: ''}
              this.$refs.formInline.resetFields()
              this.currentMenu = ''
              this.selectNodes = []
            }
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    /**
     * 展开添加菜单
     */
    handleDropClick(){
      this.addMenuModel = true
    },
    /**
     * 处理添加菜单
     */
    handelAddMenu(){
      this.$refs['formInlineMenu'].validate((valid) => {
        if(valid){
          let data = {
            title: this.formDataMenu.title,
            name: this.formDataMenu.name,
            icon: this.formDataMenu.icon,
            sysCode: this.formDataMenu.sysCode
          }
          if(this.formDataMenu.outPath && this.formDataMenu.outPath.trim() != ''){
            data.outPath = this.formDataMenu.outPath
          }
          if(this.selectNodes.length > 0 && this.selectNodes[0].id){
            data.parentId = this.selectNodes[0].id
          }
          addMenu(data).then(res => {
            if(res.data.status){
              this.$Message.success('添加成功')
              this.addMenuModel = false
              this.getMenuService(this.formDataMenu.sysCode)
              this.queryMenuData(this.selectSysCode)
              this.formDataMenu = {title: '',name: '',icon: '',sysCode: ''}
              this.$refs.formInlineMenu.resetFields()
            }
          })
        }
      })
    },
    /**
     * 删除菜单
     */
    handleTagClick(){
      //console.log(this.$refs.tree.getCheckedNodes())
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      if(checkedNodes.length == 0){
        this.$Message.warning('请至少勾选一个菜单')
        return
      }
      let menuIds = []
      checkedNodes.forEach(item => {
        menuIds.push(item.id)
      })
      console.log(menuIds)
      deleteMenu(menuIds).then(res => {
        if(res.data.status){
          this.queryMenuData(this.selectSysCode)
          this.$Message.success('删除成功')
          if(this.selectNodes.length > 0){
            this.formItem = {title: '',name: '',icon: '',sysCode: ''}
            this.$refs.formInline.resetFields()
            this.currentMenu = ''
            this.selectNodes = []
          }
        }
      })
    },
    cancelAdd(){
      this.$refs.formInlineMenu.resetFields()
    },
    /**
     * 刷新菜单数据
     */
    handleRefresh(){
      this.queryMenuData(this.selectSysCode)
      this.$Message.success('刷新成功')
    },
    /**
     * 获取菜单服务列表
     */
    getMenuService(sysCode){
      this.show = true
      menuServices().then(res => {
        this.show = false
        if(res.data.status){
          this.menuServices = res.data.data
          if(sysCode && sysCode != '' && sysCode.length > 0){
            this.selectSysCode = sysCode
          }else{
            this.selectSysCode = this.menuServices[0]
          }
          // 加载菜单数据
          this.queryMenuData(this.selectSysCode)
        }
      }).catch(()=>{
        this.show = false
      })
    },
    handleOnSelect(item){
      // 加载菜单数据
      this.queryMenuData(item.value)
    },
    handelRefresh(){
      this.getMenuService()
    }
  },
  created(){
    this.getMenuService()
  }
}
</script>

<style lang="less">
.menu{
  padding-top: 16px;
  padding-bottom: 16px;
  padding-left: 0;
  padding-right: 0;
  .menu-col{
    margin-bottom: 10px;
    .menu-box{
      max-height: 550px;
      overflow: auto;
    }
  }
  .menu-title{
    padding: 10px;
    padding-left: 0;
  }
}
</style>
